package com.itcpeng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcpeng.constant.MessageConstant;
import com.itcpeng.entity.Result;
import com.itcpeng.pojo.OrderSetting;
import com.itcpeng.service.OrderSettingService;
import com.itcpeng.util.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @PostMapping(value = "/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) {
        //读取Excel文件数据
        try {

            List<String[]> settings = POIUtils.readExcel(multipartFile);
            //把他转成ordersetting实体list
            List<OrderSetting> list = new ArrayList<OrderSetting>();
            OrderSetting os = null;
            //日期转换
            SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT);
            for (String[] arr : settings) {
                os = new OrderSetting(sdf.parse(arr[0]), Integer.valueOf(arr[1]));
                list.add(os);
            }
            if (list.size() > 0) {
                orderSettingService.doImport(list);
                return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
    }

    @PostMapping(value = "/ordersettingMonth")
    public Result ordersettingMonth(String month) {
        //调用业务查询
        List<OrderSetting> list = orderSettingService.ordersettingMonth(month);
        //转成leftobj格式{ date: 1, number: 120, reservations: 1 }
        //返回结果集
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        //每日的数据
        Map<String, Object> map = null;
        //数据格式转换
        if (list != null && list.size() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("d");
            for (OrderSetting os : list) {
                //获取日期中的天数转为整型
                map = new HashMap<String, Object>();
                map.put("date", Integer.valueOf(sdf.format(os.getOrderDate())));
                map.put("number", os.getNumber());
                map.put("reservations", os.getReservations());
                resultList.add(map);
            }
        }
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, resultList);
    }

    @PostMapping(value = "/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }


}
